package com.example.screenprojection;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.media.projection.MediaProjectionManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.provider.Settings;
import android.provider.SyncStateContract;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

import com.example.screenprojection.Utils.MyUtils;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    private static final int REQUEST_MEDIA_PROJECTION_CODE = 1;
    private static final int SERVER_FRAGMENT = 1;
    private static final int CLIENT_FRAGMENT = 2;

    private FragmentManager fragmentManager;
    private ServerFragment serverFragment;
    private ClientFragment clientFragment;

    private Button choice_button;

    private void InitView() {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        MyUtils.setScreenDensity(metrics.densityDpi);
        MyUtils.setScreenWidth(metrics.widthPixels);
        MyUtils.setScreenHeight(metrics.heightPixels);
        MyUtils.setLocalIp(getLocalIp());

        choice_button = (Button) findViewById(R.id.choice_button);
        choice_button.setOnClickListener(this);

        fragmentManager = getSupportFragmentManager();
        showFragment(SERVER_FRAGMENT);

        Request_Media_Projection_Permission();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.choice_button) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            final String[] socket = {"服务端", "客户端"};
            builder.setItems(socket, (dialogInterface, i) -> {
                if (i == 0) {
                    showFragment(SERVER_FRAGMENT);
                } else {
                    showFragment(CLIENT_FRAGMENT);
                }
                choice_button.setText(socket[i]);
            });
            builder.show();
        }
    }

    private void showFragment(int fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragments(transaction);
        switch (fragment) {
            case SERVER_FRAGMENT:
                if (serverFragment != null) {
                    transaction.show(serverFragment);
                } else {
                    serverFragment = new ServerFragment();
                    transaction.add(R.id.socket_frame, serverFragment);
                }
                break;
            case CLIENT_FRAGMENT:
                if (clientFragment != null) {
                    transaction.show(clientFragment);
                } else {
                    clientFragment = new ClientFragment();
                    transaction.add(R.id.socket_frame, clientFragment);
                }
                break;
        }
        transaction.commit();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (serverFragment != null) {
            transaction.hide(serverFragment);
        }
        if (clientFragment != null) {
            transaction.hide(clientFragment);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        InitView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MEDIA_PROJECTION_CODE) {
            if (resultCode != Activity.RESULT_OK) {
                Toast.makeText(this, "Media Projection Permission Denied", Toast.LENGTH_SHORT).show();
                return;
            }
            MyUtils.setResultCode(resultCode);
            MyUtils.setResultData(data);
        }
    }

    private void Request_Media_Projection_Permission() {
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) this.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        Intent intent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(intent, REQUEST_MEDIA_PROJECTION_CODE);
    }

    private String getLocalIp() {
        String ip = "";
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo.isConnected()) {
            ip = MyUtils.getIPv4Address(wifiManager.getDhcpInfo().serverAddress);
        } else {
            ip = MyUtils.getLocalAddress();
        }
        return ip;
    }
}